package com.jinlongchen.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jinlongchen.DBUtil;
import com.jinlongchen.model.Story;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/api/story-detail.json")
public class StoryDetailApi extends AbsApiServlet {
    @Override
    protected Object doGetInner(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException, APIException {
        int sid = Integer.parseInt(req.getParameter("sid"));

        Story story = new Story();
        story.sid = sid;
        story.audio = String.format("/get-audio?sid=%d", sid);

        //统计故事播放量
        //1、更新故事表的count
        //2、更新专辑表的count
        try (Connection c = DBUtil.getConnection()){
            //1、关闭Connecton 的自动commit，因为默认是true
            c.setAutoCommit(false);

            //2、更新story表
            try (PreparedStatement s = c.prepareStatement("UPDATE story SET count = count + 1 WHERE sid = ?")){
                s.setInt(1,sid);
                s.executeUpdate();
            }

            //3.0 根据 sid 先查出 aid
            int aid;
            try (PreparedStatement s = c.prepareStatement("SELECT aid FROM story WHERE sid = ?")) {
                s.setInt(1, sid);
                try (ResultSet rs = s.executeQuery()) {
                    // TODO: 完全不考虑 sid 没有故事对应的情况了
                    rs.next();
                    aid = rs.getInt("aid");
                }
            }

            //4、更新 album表
            try (PreparedStatement s = c.prepareStatement("UPDATE album SET count = count + 1 WHERE aid = ?")) {
                s.setInt(1, aid);
                s.executeUpdate();
            }

            // 5. 正式进行 commit
            c.commit();
        }

        try (Connection c = DBUtil.getConnection()) {
            String sql = "SELECT name FROM story WHERE sid = ?";
            try (PreparedStatement s = c.prepareStatement(sql)) {
                s.setInt(1, sid);
                try (ResultSet rs = s.executeQuery()) {
                    if (!rs.next()) {
                        throw new APIException("sid 对应的故事不存在");
                    }

                    story.name = rs.getString("name");
                    return story;
                }
            }
        }
    }
//        private final ObjectMapper objectMapper = new ObjectMapper();
//
//        @Override
//        protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//            //1、获取sid
//            req.setCharacterEncoding("utf-8");
//            int sid = Integer.parseInt(req.getParameter("sid"));
//            //2、读取story的信息
//            Story story = new Story();
//            story.sid = sid;
//            story.audio = String.format("/get-audio?sid=%d", sid);
//            try {
//                try (Connection c = DBUtil.getConnection()) {
//                    String sql = "SELECT name FROM story WHERE sid = ?";
//                    try (PreparedStatement s = c.prepareStatement(sql)) {
//                        s.setInt(1, sid);
//
//                        try (ResultSet rs = s.executeQuery()) {
//                            if (!rs.next()) {
//                                //404
//                                Object result = new Object() {
//                                    public boolean success = false;
//                                    public String reason = "sid 对应的故事不存在";
//                                };
//                                //4、json序列化
//                                String json = objectMapper
//                                        .writerWithDefaultPrettyPrinter()
//                                        .writeValueAsString(result);
//                                //5、写响应
//                                resp.setCharacterEncoding("utf-8");
//                                resp.setContentType("application/json");
//                                resp.getWriter().println(json);
//                                return;
//                            }
//
//                            story.name = rs.getString("name");
//                            System.out.println(story.name);
//
//                            //3、准备对象
//                            Object result = new Object() {
//                                public boolean success = true;
//                                public Object data = story;
//                            };
//                            //4、json序列化
//                            String json = objectMapper
//                                    .writerWithDefaultPrettyPrinter()
//                                    .writeValueAsString(result);
//                            System.out.println(json);
//                            //5、输出
//                            resp.setCharacterEncoding("utf-8");
//                            resp.setContentType("application/json");
//                            resp.getWriter().println(json);
//                        }
//                    }
//                }
//            } catch (SQLException exc) {
//                exc.printStackTrace();
//                Object result = new Object() {
//                    public boolean success = false;
//                    public String reason = exc.getMessage();
//                };
//                //4、json序列化
//                String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);
//                //5、写响应
//                resp.setCharacterEncoding("utf-8");
//                resp.setContentType("application/json");
//                resp.getWriter().println(json);
//            }
//        }
//    }
}
